import serial
import os
import time



class SerialInterface:
    def __init__(self, port='/dev/ttyS0', baudrate=9600, timeout=1):
        self.port = port
        self.baudrate = baudrate
        self.timeout = timeout
        # self.ser = None
        # self.setstate = None   #0指令模式 1数据收发模式
        # self.setgpio = setgpio
        # self.csgpio = csgpio
        # self.setctl = None
        # self.csctl = None

    def open(self):
        try:
            self.ser = serial.Serial(self.port, self.baudrate, timeout=self.timeout)
        except Exception as e:
            raise RuntimeError(f"打开串口 {self.port} 失败：{e}")

    def close(self):
        if self.ser:
            self.ser.close()

    def write(self, data):
        if not self.ser:
            raise RuntimeError(f"串口 {self.port} 未打开")

        try:
            # self.ser.write(data.encode())
            self.ser.write(data)
        except Exception as e:
            raise RuntimeError(f"发送数据失败：{e}")

    def read(self, length=1024):

        if not self.ser:
            raise RuntimeError(f"串口 {self.port} 未打开")

        try:
            # data = self.ser.read(length).decode()
            data = self.ser.read(length)
            return data
        except Exception as e:
            raise RuntimeError(f"接收数据失败： {e}")

'''
01 设备编号
03 功能码     读取保持寄存器
00 00 00 0A          Data start re
'''        
hex_data = '01 03 00 00 00 02 C4 0B'

#返回的数据为2进制：b'\x01\x03\x04\x01\x08\x022\xfa\xb8'

#hex_data = "01 03 00 00 00 0A C5 CD"
byte_data = bytes.fromhex(hex_data)
rs485Dev1 = SerialInterface(port='/dev/ttyS0')

def parse_frame(message,total_length):
 
    Rs485dict = {}
    # message = message.hex()
    if len(message) < 6:
      	raise RuntimeError("数据解析失败")
    if  message[0]==0x01 and message[1]==0x03:
        Rs485dict["温度"]=(message[3]*256+message[4])/10
        Rs485dict["湿度"]=(message[5]*256+message[6])/10
        return Rs485dict
    else:
        return Rs485dict

@init
def driver_init():
    rs485Dev1.open()

@release
def driver_release():
    rs485Dev1.close()

# 实验室气象站传感器
@report(interval=1, device_id='lab_meteorology-01', channel='default')
def report_data():
    rs485Dev1.write(byte_data)
    received_data = rs485Dev1.read()
    return parse_frame(list(received_data), len(received_data))

# if __name__  == '__main__':
#     driver_init()
#     print(report_data())
#     import time
#     time.sleep(2)
#     print(report_data())
#     driver_release()



